package com.topscomm.file.convert.factory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.stereotype.Component;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.pub.util.ConvertUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件转换多线程分发处理
 * 
 * @description:
 * @author: donghang
 * @date: 2021年3月15日下午8:13:46
 * @modify:
 */
@Component
@Slf4j
public class FileConvertDispatcher {
	/**
	 * 线程调度
	 */
	private ExecutorService executorService;

	public FileConvertDispatcher() {
		Integer availableProcessors = Runtime.getRuntime().availableProcessors();
		Integer numOfThreads = availableProcessors * 2;
		executorService = Executors.newCachedThreadPool();
		// new ThreadPoolExecutor(numOfThreads, numOfThreads, 60L,
		// TimeUnit.SECONDS,
		// new LinkedBlockingDeque<Runnable>(10));
	}

	/**
	 * 处理文件
	 * 
	 * @description:
	 * @param filePath
	 * @param targetFilePath
	 * @author: donghang
	 * @date: 2021年3月15日下午8:15:36
	 * @modify:
	 */
	public boolean handle(String filePath, String targetFilePath, String identifier) {
		// 提交到线程。进行图片转换
		try {
			Future<Boolean> future = executorService.submit(new FileConvertTask(filePath, targetFilePath, identifier));
			if (future.get() == true) {
				return true;
			} else {
				log.error("文件" + filePath + "转换错误,异常信息");
				throw new ServiceException("转换失败");
			}
		} catch (Exception e) {
			if (ConvertUtil.convertToString(e.getMessage()).contains("OutOfMemoryError")) {
				log.error("文件" + filePath + "转换错误,异常信息：内存过大");
				throw new ServiceException("文件过大，暂时无法转换，请稍后重试！");
			} else {
				log.error("文件" + filePath + "转换错误,异常信息：" + e.getMessage());
				throw new ServiceException("文件转换错误，请稍后重试！");
			}
		}
	}
}
